from api.protos.tictactoe_grpc_pb2 import Player

class GameContent:
    def __init__(self):
        self.g_size = 3 * 3
        self.index_ = 0
        self.checkerboard = [0] * 9

    def init_game(self):
        self.index_ = 0
        self.checkerboard = [0] * 9

    def refresh_checkerboard(self, index):
        value = 1 if (self.index_ & 1) == 0 else 2
        self.checkerboard[index - 1] = value
        self.index_ += 1

    def get_result(self):
        winner = Player.DEFAULT
        if self._is_slant_same_line() or self._is_vertical_same_line() or self._is_horizontal_same_line():
            winner = Player.PLAYER_A if (self.index_ & 1) == 0 else Player.PLAYER_B
            return True, winner
        return False, winner

    def _is_horizontal_same_line(self):
        find_vec = [0, 3, 6]
        for num in find_vec:
            if self.checkerboard[num] != 0 and (self.checkerboard[num] == self.checkerboard[num + 1] == self.checkerboard[num + 2]):
                return True
        return False

    def _is_vertical_same_line(self):
        find_vec = [0, 1, 2]
        for num in find_vec:
            if self.checkerboard[num] != 0 and (self.checkerboard[num] == self.checkerboard[num + 3] == self.checkerboard[num + 6]):
                return True
        return False

    def _is_slant_same_line(self):
        return self.checkerboard[0] == self.checkerboard[4] == self.checkerboard[8] or \
               self.checkerboard[2] == self.checkerboard[4] == self.checkerboard[6]
